package com.ll.arraydemo;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author 刘龙
 * @version 1.0
 */
public class ArraySortCustom {
    public static void main(String[] args) {
        int[] arr = {1, -1, 8, 0, 9};

        // bubbleSort(arr);
        bubbleSort2(arr, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Integer i1 = (Integer) o1;
                Integer i2 = (Integer) o2;
                return i1 - i2;
            }
        });

        // [-1, 0, 1, 8, 9]
        System.out.println(Arrays.toString(arr));
    }

    // 使用冒泡完成排序
    public static void bubbleSort(int[] arr) {
        int temp = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int y = 0; y < arr.length - 1 - i; y++) {
                if (arr[y] > arr[y + 1]) {
                    temp = arr[y];
                    arr[y] = arr[y + 1];
                    arr[y + 1] = temp;
                }
            }
        }
    }

    // 结合冒泡 + 定制
    public static void bubbleSort2(int[] arr, Comparator c) {
        int temp = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int y = 0; y < arr.length - 1 - i; y++) {
                // 数组排序由c.compare(arr[y], arr[y+1]) 返回的值决定
                if (c.compare(arr[y], arr[y + 1]) > 0) {
                    temp = arr[y];
                    arr[y] = arr[y + 1];
                    arr[y + 1] = temp;
                }
            }
        }
    }
}
